layui.config({
    base: "js/"
}).use(['table', 'layer', 'form', 'jquery'], function () {
    var table = layui.table,
        form = layui.form,
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        $ = layui.jquery;

    /***
     *
     * 显示友鏈
     *
     */
    table.render({
        skin: 'line',
        elem: '#linkList'
        , loading: true
        , url: '/tiLinks/queryLinkList'
        , cols: [
            [
                {type: 'checkbox', fixed: 'left'}
                , {field: 'websiteName', title: '网站名称', edit: 'text'}
                , {
                field: 'websiteUrl', title: '网站地址', edit: 'text'
            }
                , {
                field: 'authorMail', title: '站长邮箱', edit: 'text'
            }, {
                field: 'websiteDescribe', title: '网站描述', edit: 'text'
            }
                , {
                field: 'creationTime', title: '创建时间'
            }
                , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 160}
            ]
        ]
        , limit: 20
        , limits: [20, 25, 50, 100]
        , parseData: function (data) {
            /**
             * 打印数据
             *console.log(data)
             */
        }
        , page: true
        , id: 'linkListReload'
    });


    /**
     *  添加友情链接
     */
    $(".linksAdd_btn").click(function () {
        var index = layui.layer.open({
            title: "添加友情链接",
            type: 2,
            content: "linksAdd.html",
            success: function (layero, index) {
                setTimeout(function () {
                    layui.layer.tips('点击此处返回友链列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function () {
            layui.layer.full(index);
        })
        layui.layer.full(index);
    })

    //监听工具条
    table.on('tool(link)', function (obj) {
        var data = obj.data;
        //console.log(data)
        var layerIndex = layer.load(2, {time: 5 * 1000});
        if (obj.event === 'delLink') {
            layer.confirm('真的删除行么？', {title: '系统提示'}, function (index) {
                    $.ajax({
                        url: '/tiLinks/editLink',
                        data: {
                            websiteState: 1,
                            websiteId: data.websiteId
                        },
                        type: 'put',
                        success: function (data) {
                            if (data.code == 200) {
                                $.message({
                                    message: data.msg,
                                    type: 'success',
                                    showClose: true
                                });
                                obj.del();
                            } else {
                                $.message({
                                    message: data.msg,
                                    type: 'warning',
                                    showClose: true
                                });
                            }
                        }, error: function () {
                            $.message({
                                message: 'boom..',
                                type: 'error',
                                showClose: true
                            });
                        }, complete: function (XHR, TS) {

                            layer.close(index);
                            layer.close(layerIndex);
                        }
                    })
                }, function () {
                    layer.close(layerIndex);
                }
            );
        } else if (obj.event === 'editLink') {
            $.message({
                message: '直接点击单元格编辑',
                type: 'info',
                showClose: true
            });
            layer.close(layerIndex);
        } else if (obj.event === 'queryLink') {
            window.open(data.websiteUrl);

            layer.close(layerIndex);
        }

    });

    /**
     * 监听单元格编辑
     */
    table.on('edit(link)', function (obj) {
        var value = obj.value //得到修改后的值
            , data = obj.data //得到所在行所有键值
            , field = obj.field; //得到字段
        /**
         console.log(value)
         console.log(data)
         console.log(field)
         */

        const jiuData = $(this).prev().text();

        if ((field == 'websiteName')) {
            if (value == '') {
                $.message({
                    message: '网站名不能空',
                    type: 'warning',
                    showClose: true
                });
                $(this).val(jiuData)
                return false;
            }
        }

        if (field == 'websiteUrl') {
            if (value == '') {
                $.message({
                    message: '网站地址不能空',
                    type: 'warning',
                    showClose: true
                });
                $(this).val(jiuData)
                return false;
            } else {
                var str = value
                var Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
                var objExp = new RegExp(Expression);
                if (objExp.test(str) != true) {
                    $.message({
                        message: '网址格式不正确！',
                        type: 'warning',
                        showClose: true
                    });
                    $(this).val(jiuData)
                    return false;
                }
            }
        }

        if (field == 'authorMail') {
            var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
            if (value != '') {
                if (!reg.test(value)) {
                    $.message({
                        message: '邮箱格式不正确',
                        type: 'warning',
                        showClose: true
                    });
                    $(this).val(jiuData)
                    return false;
                }
            }
        }

        var layerIndex = layer.load(2, {time: 5 * 1000});
        $.ajax({
            type: "PUT",
            url: "/tiLinks/editLink",
            datatype: "json",
            data: data,
            success: function (data) {
                // console.log(data)
                if (data.code == 200) {
                    $.message({
                        message: data.msg,
                        type: 'success',
                        showClose: true
                    });
                } else {
                    $.message({
                        message: data.msg,
                        type: 'warning',
                        showClose: true
                    });
                }
            }, error: function () {
                $.message({
                    message: 'boom..',
                    type: 'error',
                    showClose: true
                });
            }, complete: function (XHR, TS) {
                layer.close(layerIndex);
            }

        });
    });

    var $ = layui.$, active = {
        /**
         * 批量删除链接
         *
         * */
        closeBtn: function () {
            var $checkbox = $('table input[type="checkbox"][name="layTableCheckbox"]');
            var $checked = $('table input[type="checkbox"][name="layTableCheckbox"]:checked');
            if ($checkbox.is(":checked")) {
                var checkStatusId = table.checkStatus('linkListReload'),
                    data = checkStatusId.data,
                    websiteId = [];

                for (var i in data) {
                    websiteId.push(data[i].websiteId)
                }

                layer.confirm('确定要删除' + data.length + '条数据么?', {title: '系统信息'}, function (index) {
                    var layerIndex = layer.load(2, {time: 5 * 1000});
                    $.ajax({
                        url: '/tiLinks/delBatchLink',
                        data: {
                            websiteState: 1,
                            websiteId: websiteId
                        },
                        type: 'PUT',
                        success: function (res) {
                            if (res.code == 200) {
                                table.reload('linkListReload', {});
                                $.message({
                                    message: res.msg,
                                    type: 'success',
                                    showClose: true
                                });

                            } else {
                                $.message({
                                    message: res.msg,
                                    type: 'warning',
                                    showClose: true
                                });
                            }
                        }, error: function (data) {
                            $.message({
                                message: '系统异常..',
                                type: 'error',
                                showClose: true
                            });
                        }, complete: function () {
                            layer.close(index);
                            layer.close(layerIndex);
                        }
                    })


                })
            } else {
                $.message({
                    message: '请选中要删除的数据',
                    type: 'warning',
                    showClose: true
                });
            }
        },
        reload: function () {
            var linkReload = $('#linkReload');

            /**
             * 搜索内容
             * 执行重载
             * 重新从第 1 页开始
             */
            table.reload('linkListReload', {
                page: {
                    curr: 1
                }
                , where: {
                    websiteName: linkReload.val()
                }
            }, 'data');

        }
    };

    /**
     * 搜索框架 搜索内容
     * @type {*|pe}
     */
    $('.searchBtn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    /**
     * 批量删除友情链接
     */
    $('.news_search .batchDel').on('click', function () {
        var layerIndex = layer.load(2, {time: 5 * 1000});
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
        layer.close(layerIndex);
    });

})
